package com.easonji.core.aop;

import java.lang.reflect.Method;

import javax.naming.NoPermissionException;

import com.easonji.core.annotion.Permission;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import com.easonji.core.shiro.check.PermissionCheckManager;

/**
 * @ClassName: PermissionAop
 * @Description: 权限自定义检查AOP
 * @Author: LiuJun
 * @date: 2018/07/18 17:18
 * @Version: 1.0
 * @Copyright: Copyright (c) 2018 - 2019
 */
@Aspect
@Component
public class PermissionAop {

    @Pointcut(value = "@annotation(com.easonji.core.annotion.Permission)")
    private void cutPermission() {
    }

    @Around("cutPermission()")
    public Object doPermission(ProceedingJoinPoint point) throws Throwable {
        MethodSignature ms = (MethodSignature) point.getSignature();
        Method method = ms.getMethod();
        Permission permission = method.getAnnotation(Permission.class);
        Object[] permissions = permission.value();
        if (permissions == null || permissions.length == 0) {
            // 检查全体角色
            boolean result = PermissionCheckManager.checkAll();
            if (result) {
                return point.proceed();
            } else {
                throw new NoPermissionException();
            }
        } else {
            // 检查指定角色
            boolean result = PermissionCheckManager.check(permissions);
            if (result) {
                return point.proceed();
            } else {
                throw new NoPermissionException();
            }
        }
    }
}
